import React, { useState, useEffect } from "react"
import { Table, Radio, Divider } from "antd"

import { request } from "../api/request"

const TablePlus = ({ url = "" }) => {
  const [selectionType, setSelectionType] = useState("checkbox")
  const [columns, setColumns] = useState([])
  const [tableData, setTableData] = useState([])
  const [flag, setFlag] = useState(true)
  const [api, setApi] = useState("")

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
      )
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === "Disabled User",
      // Column configuration not to be checked
      name: record.name,
    }),
  }

  useEffect(() => {
    if ((flag || api !== url) && url !== '') {
      request
        .get({
          url: url,
          data: [],
        })
        .then((res) => {
          setTableData(res.list)
          buildColumns(res.columns)
          setFlag(false)
        })
        .catch((e) => console.log(e))
      setApi(url)
    }
  })

  const buildColumns = (params) => {
    let buildData = []
    params.forEach((col) => {
      buildData.push({ title: col, dataIndex: col })
    })
    setColumns(buildData)
  }

  return (
    <div>
      <Table
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns}
        dataSource={tableData}
      />
    </div>
  )
}

export default TablePlus
